package be.ipl.eBar.domaine;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MapKey;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;

@SuppressWarnings("serial")
@Entity
@Table(name = "COMMANDES", schema = "EBAR")
public class Commande implements Serializable {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;
	@NotNull
	@Temporal(TemporalType.DATE)
	private Calendar date;

	@OneToMany(mappedBy = "commande", cascade = CascadeType.ALL)
	@MapKey(name="biere")
	private Map<Biere, Ligne> lignes = new HashMap<Biere, Ligne>();

	protected Commande() {
	}

	public Commande(Calendar date) {
		date.set(Calendar.HOUR, 0);
		date.set(Calendar.MINUTE, 0);
		date.set(Calendar.SECOND, 0);
		date.set(Calendar.MILLISECOND, 0);
		this.date = date;
	}

	public int getId() {
		return id;
	}

	public Calendar getDate() {
		return date;
	}

	public List<Biere> getBieres() {
		return new ArrayList<Biere>(lignes.keySet());
	}

	public Map<Biere, Ligne> getLignes() {
		return lignes;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Commande other = (Commande) obj;
		if (id != other.id)
			return false;
		return true;
	}

	public int getQuantite(Biere biere) {
		if (!lignes.containsKey(biere)) {
			return 0;
		}
		return lignes.get(biere).getQuantite();
	}

	public void addQuantite(Biere biere, int quantite) {
		if (!lignes.containsKey(biere)) {
			lignes.put(biere, new Ligne(biere, this, quantite));
			return;
		}
		Ligne ligneCourante = lignes.get(biere);
		int nouvelleQuantite = ligneCourante.getQuantite() + quantite;
		if (nouvelleQuantite <= 0) {
			lignes.remove(biere);
			return;
		}
		ligneCourante.setQuantite(nouvelleQuantite);
		lignes.put(biere, ligneCourante);
	}

}
